package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
	"xiaozhi/config"
)

func llm(prompt string, systemPrompt string, hist_messages []string) (string, error) {
	systemMsg := config.Message{
		Role:    "system",
		Content: systemPrompt,
	}
	userMsg := config.Message{
		Role:    "user",
		Content: prompt,
	}
	var messages []config.Message
	messages = append(messages, systemMsg)
	messages = append(messages, userMsg)
	payload := config.LLMConfig{
		ApiKey:      config.NewLLMConfig().ApiKey,
		ApiUrl:      config.NewLLMConfig().ApiUrl,
		Model:       config.NewLLMConfig().Model,
		Mssages:     messages,
		Stream:      true,
		Temperature: 0.5,
	}
	jsonData, _ := json.Marshal(payload)
	response, err := http.NewRequest("POST", config.NewLLMConfig().ApiUrl, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}
	response.Header.Set("Content-Type", "application/json")
	response.Header.Set("Authorization", fmt.Sprintf("Bearer %s", config.NewLLMConfig().ApiKey))
	client := &http.Client{}
	// 发送请求并获取响应
	resp, err := client.Do(response)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 流式处理响应
	var contentBuilder strings.Builder
	scanner := bufio.NewScanner(resp.Body)
	fmt.Print("content：")
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "data: ") {
			data := strings.TrimPrefix(line, "data: ")

			// 处理结束标记
			if data == "[DONE]" {
				break
			}

			// 解析JSON数据
			var result map[string]interface{}
			if err := json.Unmarshal([]byte(data), &result); err != nil {
				continue // 跳过无效数据
			}

			// 提取content字段
			if choices, ok := result["choices"].([]interface{}); ok && len(choices) > 0 {
				if choice, ok := choices[0].(map[string]interface{}); ok {
					if delta, ok := choice["delta"].(map[string]interface{}); ok {
						if content, ok := delta["content"].(string); ok {
							contentBuilder.WriteString(content)
							fmt.Print(content)
						}
					}
				}
			}
		}
	}

	return contentBuilder.String(), nil
}

func main() {
	for {

		reader := bufio.NewReader(os.Stdin) // 创建 Reader 对象
		fmt.Println("请输入内容（输入\"exit\"退出）：")

		text, err := reader.ReadString('\n') // 读取整行输入
		if err != nil {
			fmt.Println("读取输入时发生错误：", err)
			return
		}
		if text == "exit\n" {
			break
		}
		s, err := llm(text, "", nil)
		if err != nil {
			return
		}
		fmt.Println(s)
	}

}
